<?php
// +----------------------------------------------------------------------
// | OSS存储
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\common\lib\oss;

use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Log;

class Oss{

    //初始化oss客户端
    private static function createOssClient(){
        $accessKeyId = env('oss.access_key_id');
        $accessKeySecret = env('oss.access_key_secret');
        $endpoint = env('oss.endpoint');
        try {
            return new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            Log::error("初始化oss客户端异常:".$e->getMessage());
            serviceException();
        }
    }

     /**
     * 上传文件
     * @param  string     $object     目标文件
     * @param  string     $filePath    源文件
     */
    public static function uploadFile($object,$filePath){
        $bucket = env('oss.bucket');
        try {
            $ossClient = self::createOssClient();
            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            return $result['info'];
        }catch (OssException $e) {
            Log::error("OSS上传文件失败:".$e->getMessage());
            serviceException();
        }
    }

    /**
     * 上传文件
     * @param  string     $object     目标文件
     * @param  string     $content    字符串
     */
    public static function putFile($object,$content){
        $bucket = env('oss.bucket');
        try {
            $ossClient = self::createOssClient();
            $result = $ossClient->putObject($bucket, $object, $content);
            return $result['info'];
        }catch (OssException $e) {
            Log::error("OSS上传文件失败:".$e->getMessage());
            serviceException();
        }
    }

    //获取临时密钥
    public static function getTemKey(){
        $id = env('oss.access_key_id');
        $key = env('oss.access_key_secret');
        // $host的格式为 bucketname.endpoint，请替换为您的真实信息。
        $host = 'http://'.env('oss.bucket').env('oss.endpoint');
        // $callbackUrl为上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实URL信息。
        $callbackUrl = '';
        $dir = 'test/';          // 用户上传文件时指定的前缀。

        $callback_param = array(
            'callbackUrl' => $callbackUrl,
            'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType' => "application/x-www-form-urlencoded"
        );
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = str_replace('+00:00', '.000Z', gmdate('c', $now));;


        //最大文件大小.用户可以自己设置
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition;

        // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
        $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start;


        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        $response['dir'] = $dir;  // 这个参数是设置用户上传文件时指定的前缀。
        return $response;
    }


}
